/**
 * 
 */
package com.gs.practice.thread.javathreads.ch02;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import com.gs.practice.thread.AppConstants;

/**
 * @author Sabuj Das | sabuj.das@gmail.com
 *
 */
public class CharacterDisplayCanvas extends JPanel implements
		CharacterListener {

	
	/**
	 * Generated serialVersionUID
	 */
	private static final long serialVersionUID = 6744926192356598788L;
	
	protected FontMetrics fontMetrics;
	protected char[] tmpChar = new char[1];
	protected int fontHeight;
	
	
	/**
	 * 
	 */
	public CharacterDisplayCanvas() {
		setBackground(Color.WHITE);
		setBorder(BorderFactory.createEtchedBorder());
		setPreferredSize(new Dimension(300, 100));
		setFont(AppConstants.getBitstreamFont());
		fontMetrics = getFontMetrics(getFont());
		fontHeight = fontMetrics.getHeight();
	}
	
	public CharacterDisplayCanvas(CharacterSource source){
		this();
		setCharacterSource(source);
	}
	
	/**
	 * @param source
	 */
	public void setCharacterSource(CharacterSource source) {
		source.addCharacterListener(this);
		
	}

	public Dimension preferedSize(){
		return new Dimension(fontMetrics.getMaxAscent() + 10, fontMetrics.getMaxAdvance() + 10);
	}
	
	@Override
	public synchronized void newCharacter(CharacterEvent event) {
		tmpChar[0] = (char) event.getCharacter();
		repaint();
	}
	
	@Override
	public synchronized void paintComponent(Graphics graphics) {
		Graphics2D g = (Graphics2D) graphics;
        if(null != g){
        	RenderingHints hints = new RenderingHints(
    				RenderingHints.KEY_ANTIALIASING,
    				RenderingHints.VALUE_ANTIALIAS_ON);
    		hints.add(new RenderingHints(RenderingHints.KEY_RENDERING,
    				RenderingHints.VALUE_RENDER_QUALITY));

    		Graphics2D g2d = (Graphics2D) g;
    		g2d.setRenderingHints(hints);
        }
		g.setColor(Color.BLACK);
		Dimension dimension = getSize();
		g.clearRect(0, 0, dimension.width, dimension.height);
		if(tmpChar[0] == 0)
			return;
		int charWidth = fontMetrics.charWidth((int) tmpChar[0]);
		g.drawChars(tmpChar, 0, 1, (dimension.width - charWidth) / 2, fontHeight);
	}

}
